﻿Public Class frmVentasCobro

    Private _idCaja As Integer

    Public Property idCaja() As Integer
        Get
            Return _idCaja
        End Get
        Set(ByVal value As Integer)
            _idCaja = value
        End Set
    End Property


    Private _codReciboDet As Integer = 0

    Public Property codReciboDet() As Integer
        Get
            Return _codReciboDet
        End Get
        Set(ByVal value As Integer)
            _codReciboDet = value
        End Set
    End Property

    Private _codVenta As Integer = 0

    Public Property codVenta() As Integer
        Get
            Return _codVenta
        End Get
        Set(ByVal value As Integer)
            _codVenta = value
        End Set
    End Property

    Private _codCliente As Integer = 0

    Public Property codCliente() As Integer
        Get
            Return _codCliente
        End Get
        Set(ByVal value As Integer)
            _codCliente = value
        End Set
    End Property

    Private _codRecibo As Integer = 0

    Public Property codRecibo() As Integer
        Get
            Return _codRecibo
        End Get
        Set(ByVal value As Integer)
            _codRecibo = value
        End Set
    End Property

    Private _nroFactura As String = 0

    Public Property nroFactura() As String
        Get
            Return _nroFactura
        End Get
        Set(ByVal value As String)
            _nroFactura = value
        End Set
    End Property

    Dim controller As New ControllerSigeco.controller_ventas
    Dim controllerCompras As New ControllerSigeco.controller_compras

    Private Sub frmVentasCobro_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        dgvdetalle.AutoGenerateColumns = False
        cboFormaPago.SelectedIndex = 0

        oiml.CargarCombos(cboBanco, "banco", "idbanco", controllerCompras.get_Bancos_All(oiml.dbConn))

        cargarVenta()

        GroupBox2.Focus()
        txtMontoCobro.Focus()
        ControlFormaPago()
    End Sub

    Private Sub cargarVenta()

        Try

            LimpiarDetalle()

            If codVenta > 0 Then

                Dim dt As DataTable = controller.get_Ventas_ByID(oiml.dbConn, codVenta)

                If Not dt Is Nothing Then

                    nroFactura = dt.Rows(0)("nroComprobante")
                    txtFactura.Text = dt.Rows(0)("nroComprobante") & " - " & dt.Rows(0)("fecha_") & " - " & dt.Rows(0)("cliente")
                    txtSaldo.Text = Decimal.Parse(dt.Rows(0)("saldo_cobro")).ToString("N0")

                    If dt.Rows(0)("estado") = "APROBADA" And Decimal.Parse(dt.Rows(0)("saldo_cobro").ToString) > 0 Then
                        btnAgregarDetalle.Visible = True
                        btnEliminarDetalle.Visible = True
                    ElseIf dt.Rows(0)("estado") = "ANULADA" Then
                        btnAgregarDetalle.Visible = False
                        btnEliminarDetalle.Visible = False
                    Else
                        btnAgregarDetalle.Visible = False
                        'btnEliminarDetalle.Visible = False
                    End If

                    txtMontoCobro.Focus()

                End If

                Dim dtDetalle As DataTable = controller.get_Recibos_Cobro_All(oiml.dbConn, codVenta)

                If Not dtDetalle Is Nothing Then
                    codRecibo = dtDetalle.Rows(0)("idRecibo")
                    dgvdetalle.DataSource = dtDetalle
                Else
                    dgvdetalle.DataSource = Nothing
                End If

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Function ValidarCamposDetalle() As Boolean

        Dim controlCampos As Boolean = False

        If txtFactura.Text = "" Then
            ErrorProvider1.SetError(txtFactura, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtFactura, "")
        End If        '

        If cboFormaPago.Text = "" Then
            ErrorProvider1.SetError(cboFormaPago, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(cboFormaPago, "")
        End If        '

        If txtMontoCobro.Text = "" Or Not IsNumeric(txtMontoCobro.Text) Then
            ErrorProvider1.SetError(txtMontoCobro, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider1.SetError(txtMontoCobro, "")
        End If        '

        If codCliente = 0 And codRecibo = 0 Then
            MessageBox.Show("Debe seleccionar un Cliente, Favor verifique.", "Control Proveedor", MessageBoxButtons.OK, MessageBoxIcon.Information)
            controlCampos = True
        Else

        End If        '

        'If txtprecio.Text = "" Or Not IsNumeric(txtprecio.Text) Then
        '    ErrorProvider1.SetError(txtprecio, "Campo obligatorio")
        '    controlCampos = True
        'Else
        '    ErrorProvider1.SetError(txtprecio, "")
        'End If        '

        Return controlCampos

    End Function

    Private Sub btnAgregarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarDetalle.Click

        If ValidarCamposDetalle() Then
            Exit Sub
        End If

        Dim idBanco As Integer = 0
        If cboBanco.Visible Then
            idBanco = cboBanco.SelectedValue
        End If

        Dim fechaParamDiferido As String = ""
        If fechaDiferido.Visible Then
            fechaParamDiferido = fechaDiferido.Value.ToShortDateString
        End If


        If codRecibo = 0 Then
            codRecibo = controller.Insert_Recibos(oiml.dbConn, nroFactura, DateTime.Now, _
                                                  codCliente, "COBRO @CONTADO@", _
                                                  "APROBADO", oiml.idUsuario)
        End If

        If codRecibo > 0 And codVenta > 0 Then

            If controller.Insert_Recibo_Detalle(oiml.dbConn, codRecibo, codVenta, txtMontoCobro.Text, _
                                                txtObs.Text, cboFormaPago.Text, oiml.idUsuario, idCaja, _
                                                True, idBanco, txtNroCheque.Text, txtTitular.Text, fechaParamDiferido) Then
                cargarVenta()
                MessageBox.Show("Registro grabado con exito!", "Cobros", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Cobros", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If

        End If

    End Sub

    Private Sub LimpiarDetalle()
        txtMontoCobro.Text = 0
        txtObs.Text = ""
        txtMontoCobro.Focus()
    End Sub

    Private Sub btnCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()

    End Sub

    Private Sub dgvdetalle_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvdetalle.KeyDown
        If e.KeyCode = Keys.Enter Then
            If dgvdetalle.SelectedRows.Count > 0 Then

                codReciboDet = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If
        End If
    End Sub

    Private Sub dgvdetalle_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvdetalle.DoubleClick
        If dgvdetalle.SelectedRows.Count > 0 Then

            codReciboDet = dgvdetalle.SelectedRows(0).Cells(0).Value

        End If
    End Sub

    Private Sub dgvdetalle_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdetalle.CellClick
        Try

            If dgvdetalle.SelectedRows.Count > 0 Then

                codReciboDet = dgvdetalle.SelectedRows(0).Cells(0).Value

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btnEliminarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminarDetalle.Click

        If codReciboDet > 0 Then

            If MessageBox.Show("Desea eliminar el registro seleccionado?", "Cobros", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Delete_Recibo_Detalle(oiml.dbConn, codReciboDet, oiml.idUsuario, codRecibo) Then
                    cargarVenta()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Cobros", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If

        End If

    End Sub

    Private Sub txtMontoCobro_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMontoCobro.KeyDown
        If e.KeyCode = Keys.Enter Then
            cboFormaPago.Focus()
        ElseIf e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub cboFormaPago_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cboFormaPago.KeyDown
        If e.KeyCode = Keys.Enter Then
            btnAgregarDetalle_Click(sender, e)
        ElseIf e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub

    Private Sub frmVentasCobro_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If e.KeyCode = Keys.Escape Then
            Me.Close()
        End If
    End Sub



    'codigo para textbox numerico--------------inicio-------------------
    Private Sub txtprecio_changed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMontoCobro.TextChanged
        If IsNumeric(txtMontoCobro.Text) Then

            If txtMontoCobro.Text = "" Then
                txtMontoCobro.Text = Nothing
                textWithcomma = "0"
                'this property maintain the content of textbox with comma
                'this property maintain the content of textbox without comma
                textWithoutcomma = "0"
            Else
                If txtMontoCobro.Text <> "" Then
                    Dim d As Double = Convert.ToDouble(skipComma(txtMontoCobro.Text))
                    txtMontoCobro.Text = d.ToString("N0") 'd.ToString("#.#", System.Globalization.CultureInfo.InvariantCulture)
                    textWithcomma = txtMontoCobro.Text
                    'property maintain content of textbox with comma
                    'property maintain content of textbox without comma
                    textWithoutcomma = skipComma(txtMontoCobro.Text)
                End If
            End If

            txtMontoCobro.[Select](txtMontoCobro.Text.Length, 0)

        End If
    End Sub

    Public textWithcomma As String
    Public textWithoutcomma As String

    Public Function skipComma(ByVal str As String) As String
        Dim ss As String() = Nothing
        Dim strnew As String = ""
        If str = "" Then
            strnew = "0"
        Else
            ss = str.Split("."c)
            For i As Integer = 0 To ss.Length - 1
                strnew += ss(i)
            Next
        End If
        Return strnew
    End Function

    Private Sub txtprecio_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtMontoCobro.KeyPress
        If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso (e.KeyChar <> "."c) Then
            e.Handled = True
        End If

        ' only allow one decimal point
        If (e.KeyChar = "."c) AndAlso (TryCast(sender, TextBox).Text.IndexOf("."c) > -1) Then
            e.Handled = True
        End If

    End Sub
    'codigo para textbox numerico--------------inicio-------------------


    Private Sub cboFormaPago_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboFormaPago.SelectedIndexChanged
        ControlFormaPago()
    End Sub

    Private Sub ControlFormaPago()
        If cboFormaPago.Text.Contains("EFECTIVO") Then
            txtTitular.Text = ""
            lblTitular.Visible = False

            txtNroCheque.Text = ""
            lblCheque.Visible = False

            txtTitular.Visible = False
            txtNroCheque.Visible = False

            fechaDiferido.Visible = False

            cboBanco.Visible = False
            lblBanco.Visible = False
        ElseIf cboFormaPago.Text.Contains("CHEQUE") Then
            txtTitular.Text = ""
            lblTitular.Visible = True

            txtTitular.Visible = True
            txtNroCheque.Visible = True

            txtNroCheque.Text = ""
            lblCheque.Visible = True

            If cboFormaPago.Text.Contains("DIFERIDO") Then
                fechaDiferido.Visible = True
            End If

            cboBanco.Visible = True
            lblBanco.Visible = True
        End If
    End Sub


End Class